package app.sceledroid.network;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import app.sceledroid.entity.Resource;
import app.sceledroid.services.SceleService;

import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.ByteArrayBuffer;

public class DownloadHandler extends AsyncTask<Resource, Integer, Boolean> {

	private Context context;
	private DefaultHttpClient client;
	private SceleService sceleService;
	private final String PATH = "/mnt/sdcard/download/";


	private String filename;

	//private DefaultHttpClient client;

	public DownloadHandler(DefaultHttpClient client, String filename) {
		
		this.client = client;
		this.filename = filename;
	}

	@Override
	protected Boolean doInBackground(Resource ... params) {
		// TODO Auto-generated method stub
		boolean downloaded = false;
		//InputStream stream = params[0]; // response.getEntity().getContent();
		//taken from
		//http://www.helloandroid.com/tutorials/how-download-fileimage-url-your-device
		HttpGet request = new HttpGet(params[0].getUrl());
		Log.v("URL : ", params[0].getName());
		HttpResponse response;
		InputStream stream;
		
		try {	
			response = client.execute(request);
			stream = response.getEntity().getContent();


			long startTime = System.currentTimeMillis();

			Log.d("ImageManager", "download begining");

			Log.d("ImageManager", "downloaded file name:" + params[0].getName());

			Log.d("ImageManager", "download url:" + params[0]);
			Log.d("ImageManager", "downloaded file name:" + filename);

			InputStream is = stream;
			BufferedInputStream bis = new BufferedInputStream(is);
			
			File file = new File(PATH);
			if(!file.exists())
				file.mkdir();
			
			file = new File(PATH + filename);
			
			ByteArrayBuffer baf = new  ByteArrayBuffer(1024);
			int current = 0;
			
			while((current = bis.read()) != -1){
				baf.append((byte) current);
				
			}
			
			FileOutputStream fos = new FileOutputStream(file);
			fos.write(baf.toByteArray());
			
			fos.close();
			
			bis.close();
			is.close();
			
			downloaded = true;
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
		return downloaded;
	}
}
